package it.patamau.persistence;

import java.util.List;

import it.patamau.bukkit.deathmatch.DMPlayerStat;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class Hibernate {

    private static final SessionFactory sessionFactory = buildSessionFactory();

    private static SessionFactory buildSessionFactory() {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
            return new Configuration().configure().buildSessionFactory();
        }catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
            log("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }
    
    private static void log(String msg){
    	System.err.println("[HibernateUtil] "+msg);
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
    
    public static void store(Object ... os){
    	Session session = sessionFactory.getCurrentSession();
    	Transaction t = session.beginTransaction();
    	for(Object o: os){
    		session.saveOrUpdate(o);
    	}
    	commit(t);
    }
    
    private static void commit(Transaction t){
    	try{
    		t.commit();
    	}catch(HibernateException e){
    		log("unable to commit transaction: "+e.getMessage());
    		if (t != null && t.isActive()) {
    			try {
    				t.rollback();
    			} catch (HibernateException e1) {
    				log("unable to rollback");
    			}
    		}
    	}
    }
    
    public static List get(String query){
    	Session session = sessionFactory.getCurrentSession();
    	Transaction t = session.beginTransaction();
    	List l = session.createQuery(query).list();
    	commit(t);
    	return l;
    }
    
    public static void main(String args[]){
        DMPlayerStat stat = new DMPlayerStat("garbage1");
        stat.setDeaths(10);
        stat.setKills(4);
        
        store(stat);
        
        DMPlayerStat stat2 = new DMPlayerStat("garbage2");
        stat2.setDeaths(2);
        stat2.setKills(4);
        
        DMPlayerStat stat3 = new DMPlayerStat("garbage3");
        stat3.setDeaths(3);
        stat3.setKills(5);
        
        DMPlayerStat stat4 = new DMPlayerStat("garbage4");
        stat4.setDeaths(4);
        stat4.setKills(6);
        
        DMPlayerStat stat5 = new DMPlayerStat("garbage5");
        stat5.setDeaths(5);
        stat5.setKills(7);

        store(stat, stat2, stat3, stat4, stat5);
        
        List<DMPlayerStat> stats = get("from DMPlayerStat");        
        for(DMPlayerStat s: stats){
        	System.err.println(s.getName()+" "+s.getDeaths()+" "+s.getKills());
        }
    }

}
